import { SearchConvertKeyFn, SearchTransformKeyFn } from "@ant-design/pro-components";
import { Upload, message } from "antd";
import axios from "@/api/axios"
const ACTION = '/file/upload'
/**
 * @description 文件预览的方法
 * @param file
 */
export const onPreview = (file: any) => {
  window.open(file.url, '_target');
}

/**
 * @description 解析文件名称
 * @param s
 * @returns
 */
export const getFileName = (s: string): string => {
  try {
    const url = new URL(s)
    const name: string = url.pathname?.split('/')?.pop() || ''
    return name
  } catch (e) {
    return ''
  }
}
/**
 * @description 生成一个唯一的字符串
 * @returns
 */
export function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
/**
 * @description 格式化值，用于回显数据使用
 * @param value
 * @returns
 */
export const convertValue: SearchConvertKeyFn = (value = '') => {
  if (!value) return [];
  if (typeof value === 'string') {
    const arr = value?.split(',')
    return arr.map((item: any) => {
      return {
        uid: guid(),
        name: getFileName(item),
        status: 'done',
        url: item,
        response: item
      }
    })
  }
  return (value || []).map(((item: any) => {
    if (item.response) {
      item.name = getFileName(item.response)
      return item
    }
    return item
  }))
}

/**
 * @description 格式化文件列表，用于表单提交时调用
 * @param value
 * @returns
 */
export const transform: SearchTransformKeyFn = (value,namePath,allValues) => {
  // console.log({value,namePath,allValues})
  if (!value.length) return '';
  if (typeof value === 'string') {
    return value;
  }
  allValues[namePath] = value.map((item: any) => {
    return item.response || item.url
  }).join(',')
  return allValues
}

/**
 * @description 获取图片信息
 * @param file
 * @returns
 */
export const readImg = (file: File): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    const img: HTMLImageElement = new Image()
    const reader = new FileReader()
    reader.onload = function (e: any) {
      img.src = e.target?.result
    }
    reader.onerror = function (e) {
      reject(e)
    }
    reader.readAsDataURL(file)
    img.onload = function () {
      resolve(img)
    }
    img.onerror = function (e) {
      reject(e)
    }
  })
}

// 参数类型定义
type BeforeUploadParams = {
  file: File, // 文件对象
  size?: { // 文件分辨率，用于图片的校验
    x: number, // 宽
    y: number // 高
  },
  maxSize?: number, // 文件大小
}

/**
 * @description 上传前的校验方法
 * @param BeforeUploadParams
 * @returns
 */
export const beforeUpload = async ({ file, size, maxSize }: BeforeUploadParams) => {
  if (size && size.x && size.y) {
    const img: HTMLImageElement = await readImg(file)
    if (img.width !== size.x || img.height !== size.y) {
      message.error(`请上传分辨率为${size.x}px*${size.y}px的图片`)
      return Upload.LIST_IGNORE
    }
    return file
  }
  if (maxSize) {
    if (file.size < maxSize * 1048576) {
      return file
    } else {
      message.error(`请上传小于${maxSize}M的文件`)
      return Upload.LIST_IGNORE
    }
  }
  return true
}

/**
 * @description axios参数类型定义
 */
type ProgressTypes = {
  onUploadProgress?: (event: ProgressEvent) => void
}

/**
 * @description 上传文件服务，发送请求
 * @param fileData
 * @param options
 * @returns
 */
export const uploadFile = (fileData: Record<string, string | File>, options: ProgressTypes = {}): Promise<any> => {
  const data = new FormData()
  Object.keys(fileData).forEach((key: string) => {
    data.append(key, fileData[key])
  })
  return axios(ACTION, {
    method: 'POST',
    data,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    transformRequest: [function (data) {
      return data
    }],
    ...options
  })
}

/**
 * @description 自定义上传文件
 * @param options
 */
export const customRequest = (options: any) => {
  const { file, onSuccess, onError, onProgress } = options;
  const option: ProgressTypes = {
    onUploadProgress: (event: ProgressEvent) => {
      // 上传进度发生变化时调用param.progress
      console.log(event)
      onProgress(event.loaded / event.total * 100)
    }
  }
  uploadFile({ file }, option).then(res => {
    if (res.code != 0) {
      onError(res.message)
    }
    onSuccess(res)
  }).catch(err => {
    onError(err)
  })
}

export const uploadConfig = {
  convertValue,
  transform,
}


// 使用示例
// <ProFormUploadButton {...uploadConfig} label="附件" fieldProps={{ customRequest, maxCount: 1 }} buttonProps={{ type: 'primary' }} title="上传附件" colProps={{ span: 12 }} name="disposeUrl" />
